﻿using DingTalk.Core;
using DingTalk.Corp.Auth.Models;
using DingTalk.Corp.Auth.Services;

//using DingTalk.Corp.Auth.Models;
//using DingTalk.Corp.Auth.Services;
using DingTalk.Corp.Message.Models;
using DingTalk.Corp.Message.Services;
using Dispatcher.Core.DingTalk.Models;
using MiniFox.Components;
using MiniFox.Platform.Applications.Auth;
using MiniFox.Utility;

namespace Dispatcher.Core.DingTalk
{
    /// <summary>
    /// 
    /// </summary>
    [AutoRegister, SpareComponent(typeof(DingTalkEngineService))]
    public class DingTalkEngineService : EngineServiceBase
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="principal"></param>
        public DingTalkEngineService(SystemPrincipal principal) : base(principal)
        {
        }

        [AutoWired]
        public IDingTalkProvider Provider { get; set; }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        protected virtual T CreateAgentService<T>(string name) where T : DingTalkServiceBase
        {
            T _server = ComponentFactory.GetComponent<T>(name);
            return _server;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<DingTalkSendResponse> SendMessageAsync(DingTalkSendRequest request)
        {
            var dingTalkAgent = this.CreateAgentService<DingTalkAgentMessageService>(request.AccountName);
            request.Body = await GetBodyContentAsync(request);

            var users = GetDingTalkUsers(request.AccountName, request.Receiver);
            MessageResponse msgResponse;
            switch (request.MessageType)
            {
                case MessageType.Link:
                    msgResponse = await dingTalkAgent.SendLinkMessageAsync(request.Title, request.Body, request.MessageUrl, request.Image, users);
                    break;
                case MessageType.OA:
                    msgResponse = await dingTalkAgent.SendOAMessageAsync(request.HeadTitle, request.Title, request.Body, request.MessageUrl, request.Image, request.StatusDescription, request.StatusColor, users);
                    break;
                case MessageType.Text:
                default:
                    msgResponse = await dingTalkAgent.SendTextMessageAsync(request.Body, users);
                    break;
            }

            var result = await dingTalkAgent.GetMessageResultAsync(msgResponse.TaskID);
            DingTalkSendResponse response = new()
            {
                MessageId = msgResponse.RequestId,
                TaskId = msgResponse.TaskID,
                SendTime = DateTime.Now,
                OrignalResponse = msgResponse.ToJsonString(),
                ResultJson = result.ToJsonString()
            };
            this.Provider.SaveMessageResult(request, response);

            return response;
        }

        public async void UpdateStatus(DingTalkUpdateRequest request)
        {
            var dingTalkAgent = this.CreateAgentService<DingTalkAgentMessageService>(request.AccountName);
            await dingTalkAgent.UpdateMessageAsync(request.TaskId, request.StatusDescription, request.StatusColor);
        }

        private string[] GetDingTalkUsers(string name, string[] users)
        {
            var dingTalkAgent = this.CreateAgentService<DingTalkAgentAuthService>(name);
            var dingUsers = this.GetOpenAuthUser<UserInfo>(ApiGlobalKey.USER_AGENT_NAME, users);
            var userList = dingUsers.Select(u =>
            {
                var userId = u.UserID;
                if (string.IsNullOrEmpty(userId))
                {
                    userId = dingTalkAgent.GetUserIdAsync(u.UnionID).Result;
                }
                return userId;
            });
            return userList.ToArray();
        }
    }
}
